package main

import (
	"fmt"
	"time"

	"github.com/gorhill/cronexpr"
)

type CronJob struct {
	expr *cronexpr.Expression
	next time.Time
}

// 多任务调度
func main() {
	cronJobTable := make(map[string]*CronJob)
	expr := cronexpr.MustParse("*/5 * * * * * *")

	now := time.Now()
	job1 := &CronJob{
		expr: expr,
		next: expr.Next(now),
	}
	job2 := &CronJob{
		expr: expr,
		next: expr.Next(now),
	}

	cronJobTable["job1"] = job1
	cronJobTable["job2"] = job2

	for {
		now = time.Now()

		for jobName, expr := range cronJobTable {
			if expr.next.Before(now) || expr.next.Equal(now) {
				go func(jobName string) {
					fmt.Println(now, jobName)
				}(jobName)

				expr.next = expr.expr.Next(now)
				fmt.Println(jobName, "下次执行时间：", expr.next)
			}
		}

		select {
		case <-time.After(time.Microsecond * 100):
		}
	}
}
